package com.wx.task;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

/**
 * 线程状态
 * 线程中断测试
 *
 * @author wang.xun
 * @date 2023/07/25
 */
@Slf4j
public class InterruptedTest {

    /**
     * 锁
     */
    private Object lock = new Object();

    @Test
    void threadState(){
        Runnable runnable = new Runnable(){

            @Override
            public void run() {
                Thread current = Thread.currentThread();
                Thread.State state = current.getState();
                log.info("run  state :{}",state);
                synchronized (lock){
                    while (true) {
                        /**
                         * Thread.interrupted() 会清除中断标记位
                         * isInterrupted() 不会清除中断标记位
                         * 两个方法都是调用 private native boolean isInterrupted(boolean ClearInterrupted); 传入的参数 代表是否清除标记位
                         */
                        if (Thread.interrupted()) {
                            log.info("线程被中断  :{}",current.isInterrupted());
                            break;
                        }else{
                            log.info("线程未被中断");
                        }
                        /**
                         * 业务代码
                         */
//                        try {
//                            lock.wait();
//                        } catch (InterruptedException e) {
//                            log.info("线程已被中断 state:{} 中断标记为：{}", current.getState(), current.isInterrupted());
//
//                        }
                    }
                }

            }
        };



        Thread thread = new Thread(runnable);

        Thread.State state = thread.getState();
        log.info("state :{}",state);

        thread.start();
        try {
            Thread.sleep(40);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        log.info("线程已wait state:{}",thread.getState());

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 中断该线程
        thread.interrupt();


    }
}
